package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.stark.picselect.PhotoSelectorBuilder;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.interfaces.OnSelectResultListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.PrivacyVideoAdapter;
import flc.ast.adapter.VideoAdapter;
import flc.ast.bean.MyAlbumBean;
import flc.ast.databinding.ActivityVideoBinding;
import flc.ast.dialog.CategoryEditDialog;
import flc.ast.dialog.DeleteDialog;
import flc.ast.dialog.EditDialog;
import flc.ast.dialog.InfoDialog;
import flc.ast.dialog.RenameDialog;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;

public class VideoActivity extends BaseAc<ActivityVideoBinding> {

    public static String categoryName;
    private PrivacyVideoAdapter videoAdapter;
    private List<String> listShow = new ArrayList<>();
    private BasePopupView editPopup;

    @Override
    protected int onCreate() {
        return R.layout.activity_video;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivVideoEdit.setOnClickListener(this);
        mDataBinding.ivAddVideo.setOnClickListener(this);

        mDataBinding.rvVideoList.setLayoutManager(new GridLayoutManager(mContext, 2));
        videoAdapter = new PrivacyVideoAdapter();
        mDataBinding.rvVideoList.setAdapter(videoAdapter);
        videoAdapter.addChildClickViewIds(R.id.ivVideoItemEdit);
        videoAdapter.setOnItemClickListener(this);
        videoAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivVideoEdit://编辑
                categoryDialog();
                break;
            case R.id.ivAddVideo://添加视频
                PhotoSelectorBuilder.builder(this)
                        .mode(PhotoConfig.Mode.VIDEO)
                        .maxCount(10)
                        .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                            @Override
                            public void onResult(List<SelectMediaEntity> data) {
                                for (SelectMediaEntity datum : data) {
                                    String filePath = FileUtil.generateFilePath(Content.myVideo + "/" + categoryName, "." + FileUtils.getFileExtension(datum.getPath()));
                                    FileUtils.copy(datum.getPath(), filePath);
                                }
                                getData();
                                ToastUtils.showShort(getString(R.string.add_suc));
                            }
                        });
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        PlayActivity.videoPath = videoAdapter.getItem(position);
        startActivity(PlayActivity.class);
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivVideoItemEdit://编辑
                showEditDialog(position);
                break;
        }
    }

    @Override
    protected void initData() {
        getData();
        mDataBinding.tvVideoTitle.setText(categoryName);
    }

    private void getData() {
        listShow.clear();
        String path = PathUtils.getFilesPathExternalFirst() + Content.myVideo + "/" + categoryName;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            for (File file : files) {
                listShow.add(file.getPath());
            }
        }
        if (listShow != null && listShow.size() > 0) {
            videoAdapter.setList(listShow);
            mDataBinding.rvVideoList.setVisibility(View.VISIBLE);
            mDataBinding.tvVideoNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvVideoList.setVisibility(View.GONE);
            mDataBinding.tvVideoNoData.setVisibility(View.VISIBLE);
        }
    }

    private void showEditDialog(int position) {
        EditDialog dialog = new EditDialog(mContext);
        dialog.hint = getString(R.string.move_movie_library);
        dialog.setListener(new EditDialog.Ilistener() {
            @Override
            public void clickRename() {
                showRenameDialog(position);
            }

            @Override
            public void clickShare() {
                IntentUtil.shareVideo(mContext, listShow.get(position));
            }

            @Override
            public void clickAddFolder() {
                delete(position);
            }

            @Override
            public void clickInfo() {
                showInfoDialog(position);
            }

            @Override
            public void clickDelete() {
                showDeleteDialog(position);
            }
        });
        dialog.show();
    }

    private void showRenameDialog(int position) {
        RenameDialog dialog = new RenameDialog(mContext);
        dialog.setListener(new RenameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                FileUtils.rename(listShow.get(position), name + "." + FileUtils.getFileExtension(listShow.get(position)));
                getData();
            }
        });
        dialog.show();
    }

    private void showInfoDialog(int position) {
        InfoDialog dialog = new InfoDialog(mContext);
        dialog.videoPath = listShow.get(position);
        dialog.show();
    }

    private void showDeleteDialog(int position) {
        DeleteDialog dialog = new DeleteDialog(mContext);
        dialog.setListener(new DeleteDialog.Ilistener() {
            @Override
            public void clickDelete() {
                delete(position);
            }
        });
        dialog.show();
    }

    private void delete(int position) {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //从此文件夹删除
                        FileUtils.delete(listShow.get(position));
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        getData();
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                    }
                });
            }
        }, 1000);
    }

    private void categoryDialog() {
        CategoryEditDialog categoryEditDialog = new CategoryEditDialog(mContext);
//                polygonDialog.setCurrentPos(mSelectPolygonPos);
//                polygonDialog.show();
        editPopup = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(mDataBinding.ivVideoEdit).hasShadowBg(true) // 去掉半透明背景
                .asCustom(categoryEditDialog);
        editPopup.show();
        categoryEditDialog.setListener(new CategoryEditDialog.Ilistener() {
            @Override
            public void clickRename() {
                editPopup.dismiss();
                showCategoryRenameDialog();
            }

            @Override
            public void clickDelete() {
                editPopup.dismiss();
                showCategoryDeleteDialog();
            }
        });
    }

    private void showCategoryRenameDialog() {
        String path = PathUtils.getFilesPathExternalFirst() + Content.myVideo + "/" + categoryName;
        RenameDialog dialog = new RenameDialog(mContext);
        dialog.setListener(new RenameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                FileUtils.rename(path, name);
                mDataBinding.tvVideoTitle.setText(name);
            }
        });
        dialog.show();
    }

    private void showCategoryDeleteDialog() {
        DeleteDialog dialog = new DeleteDialog(mContext);
        dialog.setListener(new DeleteDialog.Ilistener() {
            @Override
            public void clickDelete() {
                deleteCategory();
            }
        });
        dialog.show();
    }

    private void deleteCategory() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        String path = PathUtils.getFilesPathExternalFirst() + Content.myVideo + "/" + categoryName;
                        //从此文件夹删除
                        FileUtils.delete(path);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        getData();
                        dismissDialog();
                        startActivity(HomeActivity.class);
                        ToastUtils.showShort(getString(R.string.delete_suc));
                    }
                });
            }
        }, 1000);
    }

}